import http from '@/static/js/request';
import util from '@/static/js/util';
import dayjs from 'dayjs';
import { defineStore } from 'pinia'
import { pswEncode, version } from '@/static/js/config';

interface AppSate {
    userInfo:Record<string, any>,
    memberInfo:Record<string, any>,
    guildInfo:Record<string, any>,
    userRole: RTCAnswerOptions<object, any>,
    accessToken: string | null,
    communityCity: Record<string, any>,
    currentCity: Record<string, any>,
    currentSite: Record<string, any>,
    currentLocation: Record<string,any>,
    showMsgBox: Boolean,
    versionStatus: string | number,
}

export const useAppStore = defineStore('appStore',{
    state: (): AppSate => ({
        userInfo: {},
        memberInfo: {},
        guildInfo: {},
        userRole: [], //1会长,2	分会长,3普通会员
        accessToken: '',
        currentCity: {},//{"code":"440800","name":"湛江市"},
        communityCity: {code: null, name: '全国'},
        currentSite: {},
        currentLocation: {},
        showMsgBox: false,
        versionStatus: false, // false审核，true发布
    }),
    getters: {
        getShowMsgBox: state => state.showMsgBox,
        getCurrentCity: state => state.currentCity,
    },
    actions: {
        // 微信登录
        wxLogin(){
            return new Promise(async (resolve,reject) => {
                const { code }: any = await uni.login({
                    provider: 'weixin'
                });
                let params = {
                  mobile: `APP-MINI@${code}`,
                  code: code,
                  grant_type: 'mobile',
                  scope: 'server',
                };
                http('post', '/auth/oauth2/token'+ util.serialize(params), {}, (data,msg) => {
                    this.accessToken = data.access_token;
                    uni.setStorageSync('accessToken', data.access_token);
                    this.getUserInfo();
                    resolve(data);
                },(msg) => {
                    reject(msg);
                }, {
                    header:{
                        Authorization : 'Basic ' + util.encryptionBase64(pswEncode)
                    }
                },'all');
            })            
        },
        //账号密码登录
        accountLogin(obj){
            return new Promise(async (resolve,reject) => {
                let params = {
                  username: obj.username,
                  password: obj.password,
                  grant_type: 'password',
                  scope: 'server',
                };
                http('post', '/auth/oauth2/token'+ util.serialize(params), {}, (data,msg) => {
                    this.accessToken = data.access_token;
                    uni.setStorageSync('accessToken', data.access_token);
                    this.getUserInfo();
                    resolve(data);
                },(msg) => {
                    reject(msg);
                }, {
                    header:{
                        Authorization : 'Basic ' + util.encryptionBase64(pswEncode)
                    }
                },'all');
            });
        },
        // 手机验证码登录
        phoneLogin(obj){
            return new Promise(async (resolve,reject) => {
                let params = {
                  mobile: `APP-SMS@${obj.phone}`,
                  code: obj.code,
                  grant_type: 'mobile',
                  scope: 'server',
                };
                http('post', '/auth/oauth2/token'+ util.serialize(params), {}, (data,msg) => {
                    this.accessToken = data.access_token;
                    uni.setStorageSync('accessToken', data.access_token);
                    this.getUserInfo();
                    resolve(data);
                },(msg) => {
                    reject(msg);
                }, {
                    header:{
                        Authorization : 'Basic ' + util.encryptionBase64(pswEncode)
                    }
                },'all');
            });
        },
        // 注册
        handleRegister(params){
            return new Promise(async (resolve,reject) => {
                http('post', '/admin/appuser/register', params, (data,msg) => {
                    resolve(data);
                },(msg) => {
                    reject(msg);
                }, {
                    header:{
                        Authorization : 'Basic ' + util.encryptionBase64(pswEncode)
                    }
                });
            });
        },
        //通过授权信息，获取用户的微信手机号码
        getPhoneNumber(code){
            return new Promise((resolve, reject) => {
                http('get', '/admin/appuser/wxPhone/' + code, {}, (data,msg) => {
                    resolve(data);
                },msg => {
                    reject(msg);
                });
            });
        },
        //绑定微信
        bindWechat(){
            return new Promise(async (resolve,reject) => {
                const { code }: any = await uni.login({
                    provider: 'weixin'
                });
                http('post','/app/user/bindMnp', code, (data,msg) => {
                    resolve(data);
                },msg => {
                    reject(msg);
                });
            })
        },
        // 获取用户信息
        getUserInfo(){
            return new Promise((resolve, reject) => {
                http('get', '/admin/appuser/info', {}, (data,msg) => {
                    this.userInfo = data.appUser;
                    if(this.userInfo.membersDate){
                        const dateToCheck = dayjs(this.userInfo.membersDate);
                        this.userInfo.isExpire = dateToCheck.isBefore(dayjs(), 'day');
                    }else{
                        this.userInfo.isExpire = true;
                    }
                    console.log(this.userInfo.isExpire);
                    uni.setStorageSync('userInfo', JSON.stringify(data.appUser));
                    resolve(data.appUser);
                },msg => {
                    reject(msg);
                });
            });
        },
        // 修改用户信息
        editUserInfo(params){
            return new Promise((resolve, reject) => {
                http('put', '/admin/appuser/edit', params, (data,msg) => {
                    // this.userInfo = data.appUser;
                    resolve(data);
                    this.getUserInfo();
                },msg => {
                    reject(msg);
                });
            });
        },
        // 判断是否过期，并提示
        checkExpire(type){
            return new Promise((resolve, reject) => {
                let isExpire = this.userInfo.isExpire;
                resolve(isExpire);
                if(isExpire || !this.userInfo.membersDate){
                    uni.showModal({
                        title: '成为会员',
                        content: '你目前不是会员(或已到期)，无法使用当前功能，成为会员后可以参加读书会的全部活动及使用平台全部功能。',
                        confirmText: '成为会员',
                        success: res => {
                            if(res.confirm){
                                uni.reLaunch({url: '/packageA/member/index'})
                            } else if(res.cancel){
                                if(type == 'backHome'){
                                    uni.reLaunch({url: '/pages/home/index'})
                                }
                            }
                        }
                    })
                }
            });
        },
        // 微信支付
        wechatPay(params){
            return new Promise((resolve, reject) => {
                http('post', '/admin/oms/pay/payment', params, (data,msg) => {
                    resolve(data);
                },msg => {
                    reject(msg);
                });
            })
        },
        //获取当前用户加入的公会
        getPTUserGuilds(){
            return new Promise((resolve, reject) => {
                http('get', '/admin/userGuilds/getPTUserGuilds', {}, (data,msg) => {
                    this.guildInfo = data;
                    // this.getGuildsMemberInfo(data.guildId);
                    resolve(data);
                },msg => {
                    reject(msg);
                });
            })
        },
        //获取公会会员信息
        getGuildsMemberInfo(guildId){
            return new Promise((resolve, reject) => {
                http('get', '/admin/userGuilds/getGuildsMemberInfo/'+ guildId, {}, (data,msg) => {
                    this.memberInfo = data;
                    resolve(data);
                },msg => {
                    reject(msg);
                });
            })
        },
        //获取当前用户角色列表
        getUserRole(){
            return new Promise((resolve, reject) => {
                http('get', '/admin/userGuilds/getUserRole', {}, (data,msg) => {
                    this.userRole = data;
                    resolve(data);
                },msg => {
                    reject(msg);
                });
            })
        },
        getLocation(){
            return new Promise((resolve, reject) => {
                if(this.currentLocation.longitude){
                    resolve(this.currentLocation);
                }else{
                    uni.getLocation({
                        type: 'gcj02',
                        success: (resLocation) => {
                            this.currentLocation.longitude = resLocation.longitude;
                            this.currentLocation.latitude = resLocation.latitude;
                            resolve(this.currentLocation);
                        },
                        fail:(err) => {
                            console.log(err);
                            reject(err);
                        }
                    });
                }
            })
        },
        //获取当前所属的城市
        getCity(){
            return new Promise((resolve, reject) => {
                uni.getLocation({
                    type: 'gcj02',
                    success: (resLocation) => {
                        this.currentLocation.longitude = resLocation.longitude;
                        this.currentLocation.latitude = resLocation.latitude;
                        uni.request({
                            url:`https://api.tianditu.gov.cn/geocoder?postStr={'lon':${resLocation.longitude},'lat':${resLocation.latitude},'ver':1}&type=wgs84&tk=50ff5bd4032e707091e7066a75efee3e`,
                            success: res => {
                                let {status,result,msg} = res.data;
                                if(status == 0){                                    
                                    this.currentCity = {
                                        code: result.addressComponent.city_code.substring(3),
                                        name: result.addressComponent.city
                                    };
                                    resolve(this.currentCity);
                                }else{
                                    uni.showToast({title:msg, icon: 'none'});
                                    reject(msg); 
                                }                            
                            }
                        })
                    },
                    fail: err => {
                        reject(err);                        
                        uni.showModal({
                            title: "GPS异常，请检查是否开启",
                            duration: 2000,
                            icon: "none"
                        });
                    }                            
                })
            })
        },
        // 获取系统版本号，如果一致，社区是正常页面，如果不一致社区是跳转到历史活动页面
        getVersion(){
            return new Promise((resolve, reject) => {
                http('get', '/admin/param/publicValue/MINI_VERSION', {}, (data,msg) => {
                    // if(data == version){
                    //     this.versionStatus = true;
                    // }else{
                    //     this.versionStatus = false;
                    // }
                    this.versionStatus = util.compareVersion(data);
                    console.log(this.versionStatus);
                    resolve(data)
                },msg => {
                    reject(msg);
                })
            })
        }
    }
})
